package handler

import (
	"context"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"github.com/garyburd/redigo/redis"
	"ihome/models"
	"ihome/utils"
	"strconv"

	"github.com/micro/go-micro/util/log"

	getUserInfo "ihome/proto/getUserInfo"
)

type GetUserInfo struct{}

// Call is a single request handler called via client.Call or the generated client code
func (e *GetUserInfo) SrvGetUserInfo(ctx context.Context, req *getUserInfo.Request, rsp *getUserInfo.Response) error {
	logs.Info("获取用户信息 GetUserInfo /api/v1.0/user")

	rsp.Code = utils.RecodeOk
	rsp.Msg = utils.RecodeText(rsp.Code)

	bm, err := utils.NewCache()
	if err != nil {
		logs.Info("redis连接失败", err)
		rsp.Code = utils.RecodeDberr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}
	sessionId := req.SessionId
	userIdObj := bm.Get(sessionId + "user_id")
	userId, _ := redis.Int(userIdObj, nil)

	user := models.User{Id: userId}
	o := orm.NewOrm()
	err = o.Read(&user)

	if err != nil {
		logs.Info("查询用户失败")
		rsp.Code = utils.RecodeDberr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}

	rsp.UserId = strconv.Itoa(user.Id)
	rsp.Name = user.Name
	rsp.Mobile = user.Mobile
	rsp.RealName = user.Real_name
	rsp.IdCard = user.Id_card
	rsp.AvatarUrl = user.Avatar_url

	return nil
}

// Stream is a server side stream handler called via client.Stream or the generated client code
func (e *GetUserInfo) Stream(ctx context.Context, req *getUserInfo.StreamingRequest, stream getUserInfo.GetUserInfo_StreamStream) error {
	log.Logf("Received GetUserInfo.Stream request with count: %d", req.Count)

	for i := 0; i < int(req.Count); i++ {
		log.Logf("Responding: %d", i)
		if err := stream.Send(&getUserInfo.StreamingResponse{
			Count: int64(i),
		}); err != nil {
			return err
		}
	}

	return nil
}

// PingPong is a bidirectional stream handler called via client.Stream or the generated client code
func (e *GetUserInfo) PingPong(ctx context.Context, stream getUserInfo.GetUserInfo_PingPongStream) error {
	for {
		req, err := stream.Recv()
		if err != nil {
			return err
		}
		log.Logf("Got ping %v", req.Stroke)
		if err := stream.Send(&getUserInfo.Pong{Stroke: req.Stroke}); err != nil {
			return err
		}
	}
}
